package com.ihd.ihardware.view.enter.view;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.CompoundButton;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.ihd.ihardware.R;
import com.ihd.ihardware.app.MyApplication;
import com.ihd.ihardware.common.AppConstans;
import com.ihd.ihardware.databinding.ActivityLoginBinding;
import com.ihd.ihardware.pojo.LoginRes;
import com.ihd.ihardware.pojo.UserInfoRes;
import com.ihd.ihardware.view.enter.viewModel.LoginViewModel;
import com.ihd.ihardware.view.tzc.main.view.BalanceActivity;
import com.ihd.ihardware.view.tzc.me.view.PerInfoActivity;
import com.tencent.mm.opensdk.modelmsg.SendAuth;

import cn.jpush.android.api.JPushInterface;
import cn.wowjoy.commonlibrary.app.Constans;
import cn.wowjoy.commonlibrary.base.BaseActivity;
import cn.wowjoy.commonlibrary.base.BaseConsumer;
import cn.wowjoy.commonlibrary.rxbus.RxBus;
import cn.wowjoy.commonlibrary.utils.AppActivityManager;
import cn.wowjoy.commonlibrary.utils.DialogUtils;
import cn.wowjoy.commonlibrary.utils.SPUtils;
import cn.wowjoy.commonlibrary.utils.ToastUtils;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class LoginActivity extends BaseActivity<ActivityLoginBinding, LoginViewModel> {
    private Disposable wxLogin;

    @Override
    protected void init(Bundle savedInstanceState) {
        mImmersionBar.statusBarDarkFont(true).init();
        binding.mtitlebar.setTitle("登录");
        binding.mtitlebar.setLeftBack(this);


        binding.forgetTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(LoginActivity.this, ForgetActivity.class);
                startActivity(i);
                finish();
            }
        });

        binding.loginTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.login(binding.username.getText().toString(), binding.psw.getText().toString());
            }
        });

        binding.wxLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = getPackageName();
                if (!MyApplication.api.isWXAppInstalled()) {
                    ToastUtils.showLong(LoginActivity.this, "请先安装微信客户端");
                    return;
                }
                MyApplication.api.sendReq(req);
            }
        });

        binding.eyeIV.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    binding.eyeIV.setBackgroundResource(R.drawable.login_btn_dispaly);
                    binding.psw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    binding.eyeIV.setBackgroundResource(R.drawable.login_btn_hide);
                    binding.psw.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });

        binding.username.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 11)
                    binding.usernameOK.setVisibility(View.VISIBLE);
                else
                    binding.usernameOK.setVisibility(View.INVISIBLE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        setRx(Constans.LOGIN, new BaseConsumer<LoginRes>() {
            @Override
            protected void onStart() {
                DialogUtils.waitingDialog(LoginActivity.this);
            }

            @Override
            protected void onSuccess(LoginRes mLiveData) {
                JsonObject mParam = new JsonObject();
                mParam.addProperty("userId", mLiveData.getData().getUserId());
                mParam.addProperty("userToken", mLiveData.getData().getUserToken());
                SPUtils.putString(Constans.GATEWAY_TOKEN, mParam.toString());
                JPushInterface.setAlias(LoginActivity.this, 0, mLiveData.getData().getUserId());
                viewModel.getUserInfo();
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(LoginActivity.this, error.getMessage());
                DialogUtils.dismiss(LoginActivity.this);
            }
        });

        setRx(AppConstans.INFO, new BaseConsumer<UserInfoRes>() {
            @Override
            protected void onStart() {
            }

            @Override
            protected void onSuccess(UserInfoRes mLiveData) {
                DialogUtils.dismiss(LoginActivity.this);
                if (TextUtils.isEmpty(mLiveData.getData().getWeight())) {
                    Intent mIntent = new Intent(LoginActivity.this, PerInfoActivity.class);
                    mIntent.putExtra("userinfo", mLiveData.getData());
                    startActivity(mIntent);
                } else {
                    SPUtils.putString(AppConstans.USER_INFO, new Gson().toJson(mLiveData.getData(), UserInfoRes.DataBean.class));
                    Intent mIntent = new Intent(LoginActivity.this, BalanceActivity.class);
                    startActivity(mIntent);
                }

                AppActivityManager.getInstance().killActivity(PerActivity.class);
                finish();
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(LoginActivity.this, error.getMessage());
                DialogUtils.dismiss(LoginActivity.this);
            }
        });

        wxLogin = RxBus.getInstance().tObservable(AppConstans.WXLOGIN, String.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String code) throws Exception {
                        viewModel.wxLogin(code);
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (wxLogin != null && !wxLogin.isDisposed())
            wxLogin.dispose();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected Class getViewModelClass() {
        return LoginViewModel.class;
    }
}
